﻿using System;

namespace AutoNZBLoader
{
    public class FeedItem
    {
        private readonly string _Title;
        public string Title
        {
            get { return _Title; }
        } 

        private readonly string _Description;
        public string Description
        {
            get { return Description; }
        }

        private readonly string _Link;
        public string Link
        {
            get { return _Link; }
        }


        private readonly long _Season;
        public long Season
        {
            get { return _Season; }
        }

        private readonly long _Episode;
        public long Episode
        {
            get { return _Episode; }
        } 


        public FeedItem(string title, string description, string link)
        {
            this._Title = title;
            this._Description = description;
            this._Link = link;

            //Get Season / Episode
            Util.TitleParser.Result r;
            try
            {
                r = Util.TitleParser.Parser.ParseTitle(_Title);
            }
            catch (Exception)
            {
                r = Util.TitleParser.Parser.ParseTitle(_Description); //An exception here is OK
            }
            _Season = r.Season;
            _Episode = r.Episode;
        }


        public void DownloadNZB(Request request)
        {
            string filename;
            using (System.Data.IDbCommand cmd = Util.Database.DB.CreateCommand())
            {
                cmd.CommandText = "select value from properties where name='NZB Download Folder'";
                filename = cmd.ExecuteScalar().ToString();
            }

            if (!filename.EndsWith("\\", StringComparison.InvariantCulture)) filename += "\\";
            filename += string.Format(System.Globalization.CultureInfo.InvariantCulture, "{0} S{1:00}E{2:00}.nzb", request.Name, Season, Episode);

            int errorCount = 0;
            while (errorCount < 3)
            {
                try
                {
                    using (System.Net.WebClient c = new System.Net.WebClient())
                    {
                        c.DownloadFile(Link, filename);
                        break;
                    }
                }
                catch (System.Net.WebException)
                {
                    errorCount++;
                }
            }
            if (errorCount != 3)
            {
                request.MarkAsDownloaded(Season, Episode, Link);
            }
        }
    }
}
